//
//  ThinkingCocosSDK.swift
//  Game105Client-mobile
//
//  Created by Developer001 on 2025/3/31.
//

import Foundation
import ThinkingSDK

@objc class ThinkingCocosSDK : NSObject, SDKDelegate {
    
    // 静态变量持有单例实例
    @MainActor
    static var instance: ThinkingCocosSDK?
    
    var viewController :UIViewController?
    
    let appid = "cdd03cec09c54d96abca6d4e1f994ace"
    let url = "https://rtsyx.higgsyx.com"
    
    @MainActor
    @objc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("@ThinkingCocosSDK launched")
        
        ThinkingCocosSDK.instance = self
        
        if let window = application.delegate?.window {
            viewController = window?.rootViewController
        }
        
        JsbSDK.onMsg("ThinkingCocosSDK.login", handler: self.login)
        JsbSDK.onMsg("ThinkingCocosSDK.setSuperProperties", handler: self.setSuperProperties)
        JsbSDK.onMsg("ThinkingCocosSDK.track", handler: self.track)
        JsbSDK.onMsg("ThinkingCocosSDK.userSet", handler: self.userSet)
        JsbSDK.onMsg("ThinkingCocosSDK.userSetOnce", handler: self.userSetOnce)
        JsbSDK.onMsg("ThinkingCocosSDK.userAdd", handler: self.userAdd)
        
        initialize()
        
        return true
    }

    var distinctId: String?
    var deviceId: String?
    
    let developer_devices: Set<String> = [ // 开发者设备列表，这些设备不进行数据提交，以免影响现有数据
//        "B1C51118-5DD9-4A1D-94F0-E0520F83D192" // ethan的iPhone12开发机
    ];
    
    func initialize() {
        deviceId = TDAnalytics.getDeviceId()
        print("deviceId: \(deviceId!)")
        if developer_devices.contains(deviceId!) { return }
        
        TDAnalytics.enableLog(false)
        let config = TDConfig(appId: appid, serverUrl: url)
        TDAnalytics.start(with: config)
        TDAnalytics.enableAutoTrack([.appStart, .appEnd, .appInstall]) // 自动采集
        TDAnalytics.enableThirdPartySharing(TDThirdPartyType.appsFlyer)
        distinctId = TDAnalytics.getDistinctId()
    }
    
    func login(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    let uid = json["uid"] as? String
                    print("@login uid is ", uid as Any)
                    if developer_devices.contains(deviceId!) { return }
                    TDAnalytics.login(uid!)
                    TDAnalytics.enableThirdPartySharing(TDThirdPartyType.appsFlyer)
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func setSuperProperties(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    print("@setSuperProperties \(json)")
                    if developer_devices.contains(deviceId!) { return }
                    TDAnalytics.setSuperProperties(json)
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func track(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    print("@track \(json)")
                    if developer_devices.contains(deviceId!) { return }
                    if let eventName = json["_track_event_name"] as? String {
                        // 从json中 删除eventName key
                        var properties = json
                        properties.removeValue(forKey: "_track_event_name")
                        TDAnalytics.track(eventName, properties: properties)
                    }
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func userSet(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    print("@userSet \(json)")
                    if developer_devices.contains(deviceId!) { return }
                    var updatedJson = json // 创建一个可变副本
                    // 遍历字典中的键
                    for (key, value) in json {
                        if key.hasPrefix("__date__"), let timestamp = value as? TimeInterval {
                            // 将时间戳转换为 Date
                            let date = Date(timeIntervalSince1970: timestamp / 1000)
                            print("Key: \(key), Date: \(date)")
                            let newKey = String(key.dropFirst(7)) // 去除 "__date__" 前缀
                            updatedJson[newKey] = date
                            updatedJson.removeValue(forKey: key)
                        }
                    }
                    TDAnalytics.userSet(updatedJson)
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func userSetOnce(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    print("@userSetOnce \(json)")
                    if developer_devices.contains(deviceId!) { return }
                    var updatedJson = json // 创建一个可变副本
                    // 遍历字典中的键
                    for (key, value) in json {
                        if key.hasPrefix("__date__"), let timestamp = value as? TimeInterval {
                            // 将时间戳转换为 Date
                            let date = Date(timeIntervalSince1970: timestamp / 1000)
                            print("Key: \(key), Date: \(date)")
                            let newKey = String(key.dropFirst(7)) // 去除 "__date__" 前缀
                            updatedJson[newKey] = date
                            updatedJson.removeValue(forKey: key)
                        }
                    }
                    TDAnalytics.userSetOnce(updatedJson)
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func userAdd(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    print("@userAdd \(json)")
                    if developer_devices.contains(deviceId!) { return }
                    TDAnalytics.userAdd(json)
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
}
